<template>
  <div class="vehicle-management">
    <h2>车辆管理</h2>

    <!-- 搜索框 -->
    <div class="search-container">
      <input
          v-model="searchName"
          type="text"
          placeholder="请输入车辆名称"
          @input="fetchVehicles" />
    </div>

    <!-- 类型名称列标题显示下拉框 -->
    <table>
      <thead>
      <tr>
        <th>车辆ID</th>
        <th>
          <!-- 点击类型名称标题时显示下拉框 -->
          <span class="dropdown-toggle" @click="toggleDropdown">{{ categoryName || '选择类型' }}</span>
          <div v-if="showDropdown" class="dropdown-menu" ref="dropdownMenu">
            <select v-model="categoryName" @change="fetchVehicles" @click.stop>
              <option value="">所有类型</option>
              <option v-for="(name, index) in uniqueCategories" :key="index" :value="name">
                {{ name }}
              </option>
            </select>
          </div>
        </th>
        <th>车辆名称</th>
        <th>描述</th>
        <th>价格</th>
        <th>库存</th>
        <th>上线时间</th>
        <th>图片</th>
        <th>油耗</th>
        <th>最高速度</th>
        <th>加速度</th>

        <th>能源类型</th>
        <th>座位数</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="vehicle in vehicles" :key="vehicle.productId">
        <td>{{ vehicle.productId }}</td>
        <td>{{ vehicle.categoryName }}</td>
        <td>{{ vehicle.name }}</td>
        <td>{{ vehicle.description }}</td>
        <!-- 价格列：如果是编辑状态，则显示输入框 -->
        <td @click="editField(vehicle, 'price')" v-if="!vehicle.isEditingPrice">
          {{ vehicle.price }}
        </td>
        <td v-if="vehicle.isEditingPrice">
          <input v-model="vehicle.newPrice" type="number" @blur="savePrice(vehicle)" />
        </td>

        <!-- 库存列：如果是编辑状态，则显示输入框 -->
        <td @click="editField(vehicle, 'stock')" v-if="!vehicle.isEditingStock">
          {{ vehicle.stock }}
        </td>
        <td v-if="vehicle.isEditingStock">
          <input v-model="vehicle.newStock" type="number" @blur="saveStock(vehicle)" />
        </td>

        <td>{{ formatDate(vehicle.createdDate) }}</td>
        <td>
          <img :src="$urlImage + vehicle.imgs" alt="车辆图片" width="50" height="50" />
        </td>
        <td>{{ vehicle.fuelConsumption }}</td>
        <td>{{ vehicle.maxSpeed }}</td>
        <td>{{ vehicle.acceleration }}</td>
        <td>{{ vehicle.energy }}</td>
        <td>{{ vehicle.seatCount }}</td>
      </tr>
      </tbody>
    </table>
    <button @click="showAddVehicleModal = true" class="add-vehicle-button">添加车辆</button>
    <div v-if="showAddVehicleModal" class="modal-overlay">
      <div class="modal-content">

        <!-- 表单内容两列 -->
        <div class="form-group">
          <div class="form-item">
            <label>车辆名称</label>
            <input v-model="newVehicle.name" type="text" />
          </div>
          <div class="form-item">
            <label>描述</label>
            <input v-model="newVehicle.description" type="text" />
          </div>
        </div>

        <div class="form-group">
          <div class="form-item">
            <label>价格</label>
            <input v-model="newVehicle.price" type="number" />
          </div>
          <div class="form-item">
            <label>库存</label>
            <input v-model="newVehicle.stock" type="number" />
          </div>
        </div>

        <div class="form-group">
          <div class="form-item">
            <label>类型</label>
            <!-- 类型改为下拉框 -->
            <select v-model="newVehicle.categoryName" @change="mapCategoryId">
              <option v-for="name in uniqueCategories" :key="name" :value="name">
                {{ name }}
              </option>
            </select>

          </div>
          <div class="form-item">
            <label>上线时间</label>
            <input v-model="newVehicle.createdDate" type="date" />
          </div>
        </div>

        <div class="form-group">
          <div class="form-item">
            <label>图片链接</label>
            <input v-model="newVehicle.imgs" type="text" />
          </div>
          <div class="form-item">
            <label>油耗</label>
            <input v-model="newVehicle.fuelConsumption" type="text" />
          </div>
        </div>

        <div class="form-group">
          <div class="form-item">
            <label>最高速度</label>
            <input v-model="newVehicle.maxSpeed" type="text" />
          </div>
          <div class="form-item">
            <label>加速度</label>
            <input v-model="newVehicle.acceleration" type="text" />
          </div>
        </div>

        <div class="form-group">
          <div class="form-item">
            <label>能源类型</label>
            <input v-model="newVehicle.energy" type="text" />
          </div>
          <div class="form-item">
            <label>座位数</label>
            <input v-model="newVehicle.seatCount" type="number" />
          </div>
        </div>

        <div class="modal-actions">
          <button @click="addVehicle">保存</button>
          <button @click="showAddVehicleModal = false">取消</button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <pagination
        :current-page="currentPage"
        :total="total"
        :page-size="pageSize"
        @update:currentPage="handlePageChange" />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination.vue';
import axios from 'axios';

export default {
  components: { Pagination },
  data() {
    return {
      categoryMapping: {
        '轿车': 1,
        'SUV': 2,
        '卡车': 3,
        // 添加所有可能的 categoryName 和对应的 categoryId
      },
      uniqueCategories: ['轿车', 'SUV', '卡车'], // 从后端获取的 categoryName 列表
      showAddVehicleModal: false,
      vehicles: [],
      categoryName: '',
      searchName: '', // 搜索框内容

      currentPage: 1,
      pageSize: 5,
      total: 0,
      showDropdown: false,
      newVehicle: {
        name: '',
        description: '',
        price: 0,
        stock: 0,
        categoryId: null, // 用于提交到后端的 ID

        createdDate: '',
        imgs: '',
        fuelConsumption: '',
        maxSpeed: '',
        acceleration: '',
        energy: '',
        seatCount: 0,
      },

    };
  },
  methods: {
    // 获取车辆数据
    async fetchVehicles() {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        categoryName: this.categoryName,
        name: this.searchName, // 添加车辆名称搜索条件
        energy: '',
        seatCount: 0,
      };
      try {
        const response = await axios.post('admins/selectAllProducts', params);
        this.vehicles = response.data.records;
        this.total = response.data.total;

        // 提取唯一的类型名称
        this.extractUniqueCategories(this.vehicles);
      } catch (error) {
        console.error('获取车辆数据失败:', error);
      }
    },

    // 提取车辆类型列表
    extractUniqueCategories(vehicles) {
      const categories = vehicles.map(vehicle => vehicle.categoryName);
      this.uniqueCategories = [...new Set(categories)]; // 使用 Set 去重
    },

    // 切换下拉框显示与隐藏
    toggleDropdown(event) {
      this.showDropdown = !this.showDropdown;
      event.stopPropagation(); // 阻止点击事件冒泡
    },

    // 处理分页变化
    handlePageChange(newPage) {
      this.currentPage = newPage;
      this.fetchVehicles();
    },

    // 格式化日期
    formatDate(date) {
      return new Date(date).toLocaleDateString(); // 格式化日期
    },

    // 点击外部区域隐藏下拉框
    handleClickOutside(event) {
      const dropdownMenu = this.$refs.dropdownMenu;
      if (dropdownMenu && !dropdownMenu.contains(event.target)) {
        this.showDropdown = false;
      }
    },

    // 启动编辑模式
    editField(vehicle, field) {
      if (field === 'price') {
        vehicle.isEditingPrice = true;
        vehicle.newPrice = vehicle.price; // 保持价格
      } else if (field === 'stock') {
        vehicle.isEditingStock = true;
        vehicle.newStock = vehicle.stock; // 保持库存
      }
    },

    // 保存价格修改
    async savePrice(vehicle) {
      if (vehicle.newPrice !== vehicle.price) {
        try {
          await axios.post('admins/updatePrice', {
            productId: vehicle.productId,
            newPrice: vehicle.newPrice,
          });
          vehicle.price = vehicle.newPrice; // 更新显示的价格
        } catch (error) {
          console.error('更新价格失败:', error);
        }
      }
      vehicle.isEditingPrice = false;
    },

    // 保存库存修改
    async saveStock(vehicle) {
      if (vehicle.newStock !== vehicle.stock) {
        try {
          await axios.post('admins/updateStock', {
            productId: vehicle.productId,
            newStock: vehicle.newStock,
          });
          vehicle.stock = vehicle.newStock; // 更新显示的库存
        } catch (error) {
          console.error('更新库存失败:', error);
        }
      }
      vehicle.isEditingStock = false;
    },
    mapCategoryId() {
      this.newVehicle.categoryId = this.categoryMapping[this.newVehicle.categoryName] || null;
    },

    addVehicle() {
      const vehicleData = { ...this.newVehicle }; // 提交的数据

      axios.post('admins/insertProducts', vehicleData)
          .then(response => {
            // 弹窗提示成功
            alert('车辆添加成功！');

            // 关闭添加弹窗
            this.showAddVehicleModal = false;

            // 清空表单数据
            this.newVehicle = {
              name: '',
              description: '',
              price: 0,
              stock: 0,
              categoryId: null, // 确保重置 categoryId
              categoryName: '',
              createdDate: '',
              imgs: '',
              fuelConsumption: '',
              maxSpeed: '',
              acceleration: '',
              energy: '',
              seatCount: 0,
            };

            // 刷新车辆列表（可选）
            this.fetchVehicles();
          })
          .catch(error => {
            // 弹窗提示失败
            alert('添加车辆失败，请重试！');
            console.error('添加车辆失败:', error);
          });
    }


  },

  mounted() {
    this.fetchVehicles(); // 加载车辆数据
    // 在组件加载后监听点击事件
    document.addEventListener('mousedown', this.handleClickOutside);
  },

  beforeDestroy() {
    // 组件销毁前移除事件监听
    document.removeEventListener('mousedown', this.handleClickOutside);
  }
};
</script>

<style scoped>
.vehicle-management {
  position: relative;
  padding: 20px;
}

.add-vehicle-button {
  margin-bottom: 20px;
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.add-vehicle-button:hover {
  background-color: #0056b3;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

table th,
table td {
  border: 1px solid #ccc;
  padding: 10px;
}

img {
  border-radius: 4px;
}

.dropdown-toggle {
  cursor: pointer;
  color: blue;
}

.dropdown-menu {
  position: absolute;
  z-index: 10;
  background-color: white;
  border: 1px solid #ccc;
  padding: 5px;
  margin-top: 5px;
}

.dropdown-menu select {
  width: 200px;
  padding: 5px;
}

.search-container {
  margin-bottom: 20px;
}

.search-container input {
  padding: 8px;
  font-size: 14px;
  width: 300px;
  margin-right: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

input[type="number"],
input[type="text"],
input[type="date"] {
  width: 100%;
  padding: 8px;
  margin-top: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

/* 弹窗遮罩层 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;  /* 确保弹窗在最上层 */
}

/* 弹窗内容 */
.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  z-index: 1001; /* 确保弹窗内容在遮罩层上 */
}

.modal-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.modal-actions button {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.modal-actions button:first-child {
  background-color: #28a745;
  color: white;
}

.modal-actions button:first-child:hover {
  background-color: #218838;
}

.modal-actions button:last-child {
  background-color: #dc3545;
  color: white;
}

.modal-actions button:last-child:hover {
  background-color: #c82333;
}

.form-group {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 15px;
}

.form-item {
  width: calc(50% - 10px); /* 每列占 50% 宽度，减去间距 */
}

.form-item label {
  display: block;
  margin-bottom: 5px;
}

.form-item input {
  width: 100%; /* 保证输入框占满整个容器 */
  padding: 8px;
  margin-top: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

</style>